package com.yqh.Interceptor;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.yqh.entity.User;
import com.yqh.exception.CustomException;
import com.yqh.utils.JwtTokenUtil;
import com.yqh.assistMapper.UserMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


/**
 * jwt 拦截器
 *
 * @author 阳秋豪
 * @createTime 2024/3/26
 */
@Component
public class JwtInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JwtTokenUtil.class);
    @Resource
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1.从请求头中获取 token
        String token = request.getHeader("token");
        if (StrUtil.isBlank(token)) {
            // 2.请求头中 token 为空，去参数中尝试获取。 如：/api/user?token=***&pageNum=1&pageSize=5
            token = request.getParameter("token");
            // 3.若 token 还为空则抛异常
            if (StrUtil.isBlank(token)) {
                throw new CustomException("无 token，请重新登录");
            }
        }
        // 4.token 存在
        User user;
        try {
            String userId = JWT.decode(token).getAudience().get(0); // 5.获取 token 中的 userId
            user = userMapper.findUserById(Integer.valueOf(userId)); // 6.获取用户
        } catch (Exception e) {
            log.error("token 验证失败，请重新登录，token={}", token, e);
            throw new CustomException("token 验证失败，请重新登录");
        }
        // 7.用户不存在
        if (user == null) {
            throw new CustomException("用户不存在，请重新登录");
        }
        // 8.用户存在
        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
            jwtVerifier.verify(token);
        } catch (JWTVerificationException e) {
            log.error("token 验证失败，请重新登录，token={}", token, e);
            throw new CustomException("token 验证失败，请重新登录");
        }
        return true;
    }
}
